import React, { useReducer } from "react";

// 历史搜索
const HistoryContext = React.createContext();

const dataReducer = (state, action) => {
  switch (action.type) {
    case "add":
      return [action.payload, ...state];
    // return state.unshift(action.payload);
    case "clear":
      return [];
    default:
      return state;
  }
};

export const HistoryProvider = ({ children }) => {
  const [historydata, dispatch] = useReducer(dataReducer, []);
  const addHistoryData = (newdata) => {
    dispatch({ type: "add", payload: newdata });
    // alert("添加了");
  };

  const clearHistoryData = () => {
    dispatch({ type: "clear" });
  };

  return (
    <HistoryContext.Provider
      value={{ historydata, addHistoryData, clearHistoryData }}
    >
      {children}
    </HistoryContext.Provider>
  );
};

export default HistoryContext;
